package com.changgou.search.controller;

import com.changgou.search.feign.SkuFeign;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.util.Page;
import com.changgou.util.UrlUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.Map;

/**
 * @Author tang.qingbo
 * @Date 2020/8/30 16:48
 * @Version 1.0
 */
@Controller
@RequestMapping("/search")
public class SkuController {
    @Autowired
    private SkuFeign skuFeign;

    @GetMapping("/list")
    public String search(@RequestParam(required = false) Map<String, String> searchMap, Model model) {
        //调用微服务进行搜索
        Map resultMap = skuFeign.search(searchMap);
        model.addAttribute("result", resultMap);

        //存储搜索条件用于页面显示
        model.addAttribute("searchMap", searchMap);

        //拼接url地址
        String url = getUrl(searchMap);
        model.addAttribute("url", UrlUtils.replateUrlParameter(url, "pageNum"));

        //去掉排序域和排序类型域的地址
        model.addAttribute("sorturl", UrlUtils.replateUrlParameter(url,"sortRule", "sortField","pageNum"));

        //分页数据获取
        Page<SkuInfo> page = new Page<>(
                //总记录数
                Long.parseLong(resultMap.get("totalElements").toString()),
                //当前页码
                Integer.parseInt(resultMap.get("pageNum").toString()),
                //每页大小
                Integer.parseInt(resultMap.get("pageSize").toString())
        );
        model.addAttribute("page", page);

        //默认拼接前缀 /templates/ 后缀 .html
        return "search";
    }

    /**
     * 追加搜索,拼接url地址
     */
    public String getUrl(Map<String, String> searchMap) {
        //初始url地址
        String url = "/search/list";

        //有输入条件,追加到url地址后面
        if (!StringUtils.isEmpty(searchMap)) {
            //拼接'?'
            url += "?";
            for (Map.Entry<String, String> entry : searchMap.entrySet()) {
                url += entry.getKey() + "=" + entry.getValue() + "&";
            }

            //去掉最后一个'&'符号
            url = url.substring(0, url.length() - 1);
        }
        return url;
    }
}
